const Controller = require('egg').Controller;

class ForumController extends Controller {
  // 列出所有论坛帖子，包括用户信息
  async list() {
    const { ctx } = this;
    const results = await this.service.forum.list();
    ctx.body = { data: results };
  }

  // 创建论坛帖子
  async create() {
    const { ctx } = this;
    const result = await this.service.forum.create();
    if (result.affectedRows === 1) {
      ctx.body = { success: true, message: 'Forum post created successfully.' };
    } else {
      ctx.body = { success: false, message: 'Creation failed.' };
    }
  }

  // 读取单个论坛帖子，包括用户信息
  async read() {
    const { ctx } = this;
    const forum = await this.service.forum.read();
    if (forum.length > 0) {
      ctx.body = { success: true, data: forum[0] };
    } else {
      ctx.body = { success: false, message: 'Forum post not found.' };
    }
  }

  // 更新论坛帖子
  async update() {
    const { ctx } = this;
    await this.service.forum.update();
    console.log();
    ctx.body = { message: 'Updated' };
    
  }

  // 删除论坛帖子
  async delete() {
    const { ctx } = this;
    const result = await this.service.forum.delete();
    if (result.affectedRows === 1) {
      ctx.body = { success: true, message: 'Forum post deleted successfully.' };
    } else {
      ctx.body = { success: false, message: 'Deletion failed.' };
    }
  }

  // 根据用户ID查找帖子，包括用户信息
  async listByUserId() {
    const { ctx } = this;
    const results = await this.service.forum.listByUserId();
    if (results.length > 0) {
      ctx.body = { success: true, data: results };
    } else {
      ctx.body = { success: false, message: 'No forum posts found for this user.' };
    }
  }
}

module.exports = ForumController;
